import tkinter as tk
from tkinter import filedialog, messagebox, ttk
import pandas as pd

PAY_WAY_MAP = {
    "招商银行信用卡(5539)": "招商银行信用卡",
    "零钱通": '微信',
    "零钱": '微信',
    "招商银行储蓄卡(4565)": "支付宝",
    "农业银行信用卡(6982)": "农业银行信用卡",
    "交通银行信用卡(3979)": "交通银行信用卡",
    "建设银行信用卡(2744)": "建设银行信用卡",
    "浦发银行信用购(原花呗)": "支付宝",
    "浦发银行信用卡(4090)": "浦发银行信用卡",
    "兴业银行信用卡(7506)": "兴业银行信用卡-星座卡",
    "兴业银行信用卡(5807)": "兴业银行信用卡-桃花卡",
    "花呗": '支付宝',
    "账户余额": '支付宝',
    "浦发银行信用购(原花呗)&红包": '支付宝',
    "浦发银行信用购(原花呗)&花呗立减": '支付宝',
    "浦发银行信用购(原花呗)&红包&花呗立减": '支付宝',
    "浦发银行信用购(原花呗)&支付宝随机立减": '支付宝',
    "农业银行信用卡(6982)&支付宝随机立减": "农业银行信用卡",
    "农业银行信用卡(6982)&红包&农业银行立减": "农业银行信用卡",
    "农业银行信用卡(6982)&农业银行立减": "农业银行信用卡",
    "兴业银行信用卡(7506)&红包": "兴业银行信用卡-星座卡",
    "光大银行信用卡(6498)&光大银行立减": "光大银行信用卡",
    "浦发银行信用卡(4090)&红包": "浦发银行信用卡",
}


def select_file():
    selected_option = combobox.get()
    if not selected_option:
        messagebox.showwarning("警告", "请选择一个选项")
        return
    file_path = filedialog.askopenfilename(filetypes=[("Excel files", "*.xls *.xlsx")])
    if file_path:
        read_excel_file(file_path, selected_option)


def read_excel_file(file_path, type='微信'):
    try:
        if file_path.endswith('.xlsx') or file_path.endswith('.xls'):
            new_data_objects = []
            if type == '微信':
                # 忽略前16行文件
                df = pd.read_excel(file_path, skiprows=16)
                print(f"Read Excel file: {file_path}")
                data_objects = df.to_dict(orient='records')
                for data_object in data_objects:
                    # 过滤掉其他-打开拼多多，领更多现金红包的数据
                    if not (data_object['交易类型'] == "其他" and data_object[
                        '交易对方'] == "打开拼多多，领更多现金红包") and data_object[
                        '交易类型'] != "转入零钱通-来自零钱":
                        # 去除金额中的人民币符号
                        # amount = data_object['金额(元)'].replace('￥', '')
                        new_data_object = {
                            "日期": data_object['交易时间'],
                            "收支类型": data_object['收/支'],
                            "金额": data_object['金额(元)'],
                            "类别": data_object['交易类型'],
                            "子类别": data_object['交易对方'],
                            "所属账本": '日常账本',
                            "收支账户": PAY_WAY_MAP[data_object['支付方式']] if data_object[
                                                                                    '支付方式'] in PAY_WAY_MAP else
                            data_object['支付方式'],
                            "备注": data_object['商品'],
                        }
                        if new_data_object['类别'] == '亲属卡交易' and new_data_object['子类别'] == '爸爸':
                            new_data_object['类别'] = '送礼'
                            new_data_object['子类别'] = '爸亲密付'
                        if new_data_object['类别'] == '商户消费' and new_data_object['子类别'] == '叮当快药':
                            new_data_object['类别'] = '医疗'
                            new_data_object['子类别'] = '买药'
                        if new_data_object['类别'] == '商户消费' and new_data_object['子类别'] == '百川燃气有限公司':
                            new_data_object['类别'] = '居家'
                            new_data_object['子类别'] = '燃气费'
                        if new_data_object['类别'] == '商户消费' and new_data_object['子类别'] == '绿能充锋充电桩':
                            new_data_object['类别'] = '交通'
                            new_data_object['子类别'] = '电车充电'
                        if new_data_object['类别'] == '商户消费' and new_data_object['子类别'] in ['美团平台商户',
                                                                                                   '饿了么']:
                            new_data_object['类别'] = '餐饮'
                            new_data_object['子类别'] = '餐饮'
                        if '停车' in new_data_object['类别'] or '停车' in new_data_object['子类别'] or \
                                '停车' in new_data_object['备注']:
                            new_data_object['类别'] = '交通'
                            new_data_object['子类别'] = '停车费'
                        new_data_objects.append(new_data_object)
            elif type == '支付宝':
                # 忽略前16行文件
                df = pd.read_excel(file_path, skiprows=24)
                print(f"Read Excel file: {file_path}")
                data_objects = df.to_dict(orient='records')
                for data_object in data_objects:
                    # 过滤掉其他-打开拼多多，领更多现金红包的数据
                    if data_object['收/支'] != "不计收支":
                        new_data_object = {
                            "日期": data_object['交易时间'],
                            "收支类型": data_object['收/支'],
                            "金额": data_object['金额'],
                            "类别": data_object['交易分类'],
                            "子类别": data_object['交易对方'],
                            "所属账本": '日常账本',
                            "收支账户": PAY_WAY_MAP[data_object['收/付款方式']] if data_object[
                                                                                       '收/付款方式'] in PAY_WAY_MAP else
                            data_object['收/付款方式'],
                            "备注": data_object['商品说明'] if data_object['商品说明'] not in ["收钱码收款",
                                                                                               "二维码支付",
                                                                                               '经营码交易'] and not
                                                               data_object['商品说明'].isdigit() else '',
                        }
                        if '停车' in new_data_object['类别'] or '停车' in new_data_object['子类别'] or \
                                '停车' in new_data_object['备注']:
                            new_data_object['类别'] = '交通'
                            new_data_object['子类别'] = '停车费'
                        if new_data_object['类别'] == '交通出行':
                            new_data_object['类别'] = '交通'
                        if new_data_object['子类别'] == "北京公共交通控股（集团）有限公司":
                            new_data_object['子类别'] = '公交'
                            new_data_object['备注'] = ''
                        if new_data_object['子类别'] == "高德打车":
                            new_data_object['子类别'] = '打车'
                        if new_data_object['子类别'] == "北京轨道交通路网管理有限公司":
                            new_data_object['子类别'] = '地铁'
                        if new_data_object['类别'] == "充值缴费" and new_data_object['子类别'] in ["中国移动",
                                                                                                   "中国联通"]:
                            new_data_object['类别'] = '居家'
                            new_data_object['子类别'] = '话费'
                        if new_data_object['类别'] == "日用百货":
                            if new_data_object['备注']:
                                new_data_object['备注'] += "--" + new_data_object['子类别']
                            else:
                                new_data_object['备注'] = new_data_object['子类别']
                            new_data_object['类别'] = '购物'
                            new_data_object['子类别'] = '超市购物'
                        if new_data_object['类别'] == "服饰装扮":
                            if new_data_object['备注']:
                                new_data_object['备注'] += "--" + new_data_object['子类别']
                            else:
                                new_data_object['备注'] = new_data_object['子类别']
                            new_data_object['类别'] = '购物'
                            new_data_object['子类别'] = '衣服鞋包'
                        if new_data_object['类别'] == "餐饮美食":
                            if new_data_object['备注']:
                                new_data_object['备注'] += "--" + new_data_object['子类别']
                            else:
                                new_data_object['备注'] = new_data_object['子类别']
                            new_data_object['类别'] = '餐饮'
                            new_data_object['子类别'] = '餐饮'
                        new_data_objects.append(new_data_object)
            if new_data_objects:
                output_file_path = filedialog.asksaveasfilename(defaultextension=".xlsx",
                                                                filetypes=[("Excel files", "*.xlsx")])
                if output_file_path:
                    new_df = pd.DataFrame(new_data_objects)
                    new_df.to_excel(output_file_path, index=False)
                    messagebox.showinfo("成功", f"数据已保存到 {output_file_path}")
                    exit_program()
        else:
            print(f"Unsupported file type: {file_path}")
            return None
    except Exception as e:
        print(f"Error reading {file_path}: {e}")
        return None


def exit_program():
    root.destroy()


if __name__ == '__main__':
    # 创建主窗口
    root = tk.Tk()
    root.title("改写账单小程序")
    root.geometry("400x200")

    # 创建标签
    label1 = tk.Label(root, text="账单类型:")
    label1.pack(pady=5)

    # 创建下拉框
    options = ["微信", "支付宝", "抖音"]
    combobox = ttk.Combobox(root, values=options)
    combobox.pack(pady=5)

    # 创建文件选择按钮
    select_button = tk.Button(root, text="选择文件", command=select_file)
    select_button.pack(pady=5)

    # 创建取消按钮
    cancel_button = tk.Button(root, text="取消", command=root.quit)
    cancel_button.pack(pady=5)

    # 运行主循环
    root.mainloop()
